import React, { Component } from 'react';
import type { ConnectProps } from 'umi';
import { connect, history } from 'umi';
import { Tag, message } from 'antd';
import groupBy from 'lodash/groupBy';
import moment from 'moment';
import type { NoticeItem } from '@/models/global';
import type { CurrentUser } from '@/models/user';
import type { ConnectState } from '@/models/connect';
import NoticeIcon from '../NoticeIcon';
import styles from './index.less';
import { readAll } from '@/services/public';

export type GlobalHeaderRightProps = {
  notices?: NoticeItem[];
  msgs?: NoticeItem[];
  currentUser?: CurrentUser;
  fetchingNotices?: boolean;
  onNoticeVisibleChange?: (visible: boolean) => void;
  onNoticeClear?: (tabName?: string) => void;
} & Partial<ConnectProps>;

interface GlobalHeaderRightState {
  intervalN: any;
  tabKey: string;
  loading: boolean;
}

class GlobalHeaderRight extends Component<GlobalHeaderRightProps, GlobalHeaderRightState> {

  constructor(props: GlobalHeaderRightProps) {
    super(props);

    this.state = {
      intervalN: undefined,
      tabKey: 'notification',
      loading: false
    };
  }

  componentDidMount() {
    const { dispatch, currentUser } = this.props;
    const { intervalN } = this.state
    if (currentUser && currentUser !== {} && currentUser.system) {
      if (dispatch) {
        dispatch({
          type: 'global/fetchNotices',
          payload: {
            read: false
          }
        });
      }
      if ( currentUser.system == "cm") {
        if (!intervalN && currentUser.selectCorpId) {
          let interval: number = 0;
          interval = window.setInterval(() => {
            if (dispatch) {
              dispatch({
                type: 'global/fetchNotices',
                payload: {
                  read: false
                }
              });
            }
          }, 20000);
    
          this.setState({
            intervalN: interval
          })
        }
      }
    }
  }

  componentWillUnmount() {
    if (this.state.intervalN) {
      clearInterval(this.state.intervalN);
    }
  }

  changeReadState = (clickedItem: NoticeItem): void => {
    const { id, read, url } = clickedItem;
    const { dispatch } = this.props;

    if (!read) {
      if (dispatch) {
        dispatch({
          type: 'global/changeNoticeReadState',
          payload: id,
        });
      }
    }
    if (url) {
      window.open(url, '_blank');
    }
  };

  handleNoticeClear = async () => {
    const { dispatch, currentUser } = this.props;
    this.setState({
      loading: true
    })
    const param: any = {};
    if (currentUser) {
      if (currentUser.system == 'cm') {
        if (currentUser.selectType == '1') {
          param.type = 'CONSTRUCTION_UNIT';
        } else if (currentUser.selectType == '2') {
          param.type = 'OWNER_INSPECTION';
        } else if (currentUser.selectType == '3') {
          param.type = 'LABOUR_INSPECTION';
        } else {
          param.type = 'CONSTRUCTION_UNIT';
        }
        param.targetId = currentUser.selectCorpId;
      } else if (currentUser.system == 'bk') {
        param.type = 'BANK';
        param.targetId = currentUser.bankId;
      } else if (currentUser.system == 'ls') {
        param.type = 'OA_INSPECTION';
        param.targetId = 0;
      } else if (currentUser.system == 'gs') {
        param.type = 'TP_INSPECTION';
        param.targetId = currentUser.bankId;
      }
    }

    const res = await readAll(param);
    this.setState({
      loading: false
    })
    if (res && res.success) {
      if (dispatch) {
        dispatch({
          type: 'global/clearNotices'
        });
      }
      this.tabChange('message');
    }else{
      message.error(res.errMsg)
    }
  };

  getNoticeData = (): NoticeItem[] => {
    const { notices = [] } = this.props;
    
    if (!notices || notices.length === 0 || !Array.isArray(notices)) {
      return [];
    }

    const newNotices = notices.map((notice) => {
      const newNotice = { ...notice };

      newNotice.type = 'notification';
      
      if (newNotice.gmtCreate) {
        newNotice.gmtCreate = moment(notice.gmtCreate as string).fromNow();
      }

      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }

      return newNotice;
    });
    return newNotices
  };

  getMsgData = (): NoticeItem[] => {
    const { msgs } = this.props;
    
    if (!msgs || msgs.length === 0 || !Array.isArray(msgs)) {
      return [];
    }

    const newMsgs = msgs.map((notice) => {
      const newNotice = { ...notice };

      newNotice.type = 'message';
      
      if (newNotice.gmtCreate) {
        newNotice.gmtCreate = moment(notice.gmtCreate as string).fromNow();
      }

      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }

      return newNotice;
    });
    return newMsgs
  };

  getUnreadData = (noticeData: Record<string, NoticeItem[]>) => {
    const unreadMsg: Record<string, number> = {};
    Object.keys(noticeData).forEach((key) => {
      const value = noticeData[key];

      if (!unreadMsg[key]) {
        unreadMsg[key] = 0;
      }

      if (Array.isArray(value)) {
        unreadMsg[key] = value.filter((item) => !item.read).length;
      }
    });
    return unreadMsg;
  };

  clickMore = () => {
    const { currentUser } = this.props;
    if (currentUser) {
      if (currentUser.system == "cm") {
        history.push('/construction/message');
      } else if (currentUser.system == "bk") {
        history.push('/bank/index');
      } else if (currentUser.system == "ls") {
        history.push('/laborSupervision/index');
      } else if (currentUser.system == "gs") {
        history.push('/guarantee/message');
      }
    }
  }

  tabChange = (title: string) => {
    const { dispatch } = this.props;
    this.setState({
      tabKey: title
    })
    if (title == 'message') {
      if (dispatch) {
        dispatch({
          type: 'global/fetchNotices',
          payload: {
            read: true
          }
        });
      }
    }
  }

  render() {
    const { currentUser, onNoticeVisibleChange } = this.props;
    const { tabKey, loading } = this.state;
    const noticeData = tabKey == 'message' ? this.getMsgData() : this.getNoticeData();
    // loading={fetchingNotices}
    return (
      <NoticeIcon
        className={styles.action}
        count={currentUser && currentUser.unreadCount}
        onItemClick={(item) => {
          this.changeReadState(item as NoticeItem);
        }}
        loading={loading}
        clearText="全部已读"
        viewMoreText="查看更多"
        activeKey={tabKey}
        onClear={this.handleNoticeClear}
        onPopupVisibleChange={onNoticeVisibleChange}
        onViewMore={this.clickMore}
        onTabChange={this.tabChange}
      >
        <NoticeIcon.Tab
          tabKey="notification"
          count={0}
          list={noticeData}
          title="未读"
          emptyText="没有未读消息"
          showClear={true}
          showViewMore
        />
        <NoticeIcon.Tab
          tabKey="message"
          count={0}
          list={noticeData}
          title="已读"
          emptyText="没有已读消息"
          showClear={false}
          showViewMore
        />
      </NoticeIcon>
    );
  }
}

export default connect(({ user, global, loading }: ConnectState) => ({
  currentUser: user.currentUser,
  collapsed: global.collapsed,
  fetchingMoreNotices: loading.effects['global/fetchMoreNotices'],
  fetchingNotices: loading.effects['global/fetchNotices'],
  notices: global.notices,
  msgs: global.msge,
}))(GlobalHeaderRight);
